package com.helloandroid.view

import android.content.Context
import android.util.AttributeSet
import com.helloandroid.tools.MyLog
import java.util.*

class TickTextView @JvmOverloads constructor(
        ctx: Context,
        attrs: AttributeSet? = null,
        defStyle: Int = 0
) : androidx.appcompat.widget.AppCompatTextView(ctx,attrs,defStyle) {

    var tickUpdate:(()->Unit)? = null
    var timer: Timer? = null

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        MyLog.info("=======TickTextView onAttachedToWindow called!")
        startTimer()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        MyLog.info("=======TickTextView onDetachedFromWindow called!")
        stopTimer()
    }

    fun stopTimer(){
        timer?.cancel()
        timer = null
    }

    fun startTimer(){
        timer?.cancel()
        timer = null

        timer = Timer()
        timer?.schedule(object : TimerTask() {
            override fun run() {
                if (tickUpdate != null){
                    post {
                        tickUpdate?.invoke()
                    }
                }
            }
        },0,2000L)
    }
}